package com.example.rabbitmq;

import com.example.domain.User;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * producer->mqbroker->exchage->queue->consumer
 */
@Component
public class ConsumerAckListener {

    /*@RabbitListener(queues = "demo.queue")
    public void receive(User user) {
        System.out.println("user = " + user);
    }*/

    @RabbitListener(bindings = {@QueueBinding(value = @Queue(value = "demo1.queue"), exchange = @Exchange(value = "amq.direct"), key = "demo1.queue")})
    public void getDirectMessage(User user, Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 模拟执行任务
//            Thread.sleep(1000);
//            // 模拟异常
//            int i = 1 / 0;
            System.out.println("user = " + user);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            System.out.println("返回队列再次处理" + user);
            channel.basicNack(deliveryTag, false, true);
        }
    }

}
